package org.openapi.domain;

import lombok.Data;

import java.util.Map;

/**
 * 模型字段
 */
@Data
public class ApiField {
    /** 主键ID **/
    private Long id;

    /** 所属模型 **/
    private Long modelId;

    /** 字段类型 **/
    private Integer type;

    /** 字段代码 **/
    private String code;

    /** 字段名称 **/
    private String name;

    /** 长度 **/
    private Integer minLength;

    /** 长度 **/
    private Integer maxLength;

    /** 小数位 **/
    private Integer scale;

    /** 可为空 **/
    private Boolean nullable;

    /** 验证规则 **/
    private String rules;

    /** 默认值 **/
    private String defaults;


    /**
     * 类型转换
     * @param data
     * @return
     */
    public void fromMap(Map data){
        if(!data.containsKey("id") || !data.containsKey("model_id")){
            return;
        }
        setId(Long.parseLong(data.get("id").toString()));
        setModelId(Long.parseLong(data.get("model_id").toString()));
        setType(Integer.parseInt(data.get("type").toString()));
        setCode(data.get("code").toString());
        setName(data.get("name").toString());

        if(data.get("max_length") == null){
            setMaxLength(0);
        }else{
            setMaxLength(Integer.parseInt(data.get("max_length").toString()));
        }

        if(data.get("min_length") == null){
            setMinLength(0);
        }else{
            setMinLength(Integer.parseInt(data.get("min_length").toString()));
        }

        if(data.get("scale") == null){
            setScale(0);
        }else{
            setScale(Integer.parseInt(data.get("scale").toString()));
        }

        if(data.get("nullable") == null){
            setNullable(false);
        }else{
            setNullable("Y".equals(data.get("nullable").toString()));
        }

        if(data.get("rules") != null) {
            setRules(data.get("rules").toString());
        }
        if(data.get("defaults") != null) {
            setDefaults(data.get("defaults").toString());
        }
    }
}
